import {NextRequest, NextResponse} from "next/server";
import {cookies} from "next/headers";
import {cache} from "react";
import {jwtVerify} from "jose";


const JWT_COOKIE = 'sessionToken'
const JWT_DURATION = 14 * 24 * 60 * 60 * 1000 // 14天
const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET)

// 每个页面最多执行一次, 缓存
const decodedSessionToken = cache(async (sessionToken) => {
    try {
        // navbar用到了, 会重复执行两次(layout+page)
        const {payload} = await jwtVerify(sessionToken, JWT_SECRET)
        return payload
    } catch (err) {
        // 如果客户端篡改了cookie, 这里就会报错, 因为jwt解析错误
        console.warn('Invalid JWT', err)
    }
})

export async function GET(req, res) {
    const sessionToken = cookies().get(JWT_COOKIE)?.value
    if (sessionToken) {
        return NextResponse.json({user: await decodedSessionToken(sessionToken)})
    }
    return NextResponse.json({error: 'not user'})
}